package proxies.classes.user
{
	import core.events.PutIoErrorEvent;
	import core.events.PutIoResultEvent;
	
	import proxies.Proxy;
	import proxies.classes.user.events.UserError;
	import proxies.classes.user.events.UserFriendsResponse;
	import proxies.classes.user.events.UserInfoResponse;
	
	public class UserProxy extends Proxy implements IUserProxy
	{
		
		public static const NAME:String = "user";
		
		public static const METHOD_INFO:String = 'info';
		public static const METHOD_FRIENDS:String = 'friends';
		
		public function UserProxy()
		{
			super(NAME);
		}
		
		public function userInfo():void
		{
			sendRequest(METHOD_INFO, onUserInfoResult, onError);
		}
		
		public function userFriends():void
		{
			sendRequest(METHOD_FRIENDS, onUserFriendsResult, onError);	
		}
		
		private function onUserInfoResult(result:PutIoResultEvent):void
		{
			var userItem:UserItem = new UserItem(result.results[0]);
			
			var userInfoResponse:UserInfoResponse = new UserInfoResponse(userItem, result.bubbles, result.cancelable);
			
			dispatchEvent(userInfoResponse);
		}
		
		private function onUserFriendsResult(result:PutIoResultEvent):void
		{
			var friends:Array = new Array();
			var currentItem:FriendItem;
			
			for(var i:int=0; i < result.nbResults; i++)
			{		
				currentItem = new FriendItem(result.results[i]);
				friends.push(currentItem);
			}
			
			var userFriendsResponse:UserFriendsResponse = new UserFriendsResponse(friends, result.bubbles, result.cancelable);
			
			dispatchEvent(userFriendsResponse);
		}
		
		/**
		 * Function called if list method return an error
		 * 
		 * @param _error Error returned
		 */			
		private function onError(error:PutIoErrorEvent):void
		{
			//Add error message
			var userError:UserError = new UserError(error.errorMessage, error.bubbles, error.cancelable);
			
			//Fire event
			dispatchEvent(userError);
		}	
	}
}